package com.tulele.vtool.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tulele.vtool.mapper.OrderInfoMapper;
import com.tulele.vtool.mapper.UserPromotionSettleInfoMapper;
import com.tulele.vtool.model.*;
import com.tulele.vtool.service.*;
import com.tulele.vtool.utils.*;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.tulele.vtool.wechat.handler.*;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
@Slf4j
@Service
public class OrderInfoServiceImpl implements IOrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private IVipInfoService vipInfoService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IUserInviteIncomeInfoService userInviteIncomeInfoService;

    @Autowired
    private IUserPromotionSettleInfoService userPromotionSettleInfoService;

    @Autowired
    private ILookArticleInfoService lookArticleInfoService;

    @Autowired
    private IBrandPromotionSettleInfoService brandPromotionSettleInfoService;

    @Autowired
    private IBrandPromotionPayUserInfoService brandPromotionPayUserInfoService;

    @Autowired
    private IUserBrandInfoService userBrandInfoService;

    @Autowired
    private UserPromotionSettleInfoMapper userPromotionSettleInfoMapper;

    @Autowired
    @Lazy
    protected MenuHandler menuHandler;

    @Autowired
    @Lazy
    protected MsgHandler msgHandler;

    @Autowired
    private IMessageDictInfoService messageDictInfoService;

//    @Autowired
//    private PlatformSysInfoConfig platformSysInfoConfig;

    @Autowired
    private UserGroupGzhService userGroupGzhService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

//    @Value("${buyVipMessagePushTempID}")
//    private String buyVipMessagePushTempID;
//
//    @Value("${pushBuyVipTempID}")
//    private String pushBuyVipTempID;

//    @Value("${spring.profiles.active}")
//    private String springProfilesActive;

//    @Value("${wxShareImgPath}")
//    private String wxShareImgPath;

    /**
     * 微信支付佣金余额前缀
     */
    private static final String WECHATPAYACCOUNTBALANCELAST = "WECHATPAYACCOUNTBALANCELAST:";

    @Override
    public int doRecordOrderInfo(OrderInfo orderInfo) {
        return orderInfoMapper.addOrderInfo(orderInfo);
    }

    @Override
    public void doPayCallBackProcess(OrderInfo orderInfo, PlatformSysInfo platformSysInfo, WxMpServiceImpl weixinService) {

        double vipPriceInOrder = orderInfo.getTotalAmount().doubleValue();

        //根据订单ID获取订单信息
        OrderInfo orderInfoInDB = orderInfoMapper.queryOrderSimpleInfo(orderInfo.getOrderId());
        if (orderInfoInDB == null) {
            return;
        }

        //如果实际支付价格小于数据库中订单价格，则不做处理
        if (orderInfoInDB.getTotalAmount().doubleValue() > vipPriceInOrder) {
            return;
        }

        //如果订单状态为已经处理，则不做处理
        if (orderInfoInDB.getTransStatus().intValue() != SysConstant.ORDER_PRE_PAY_STATUS) {
            return;
        }

        //查询数据库中金币信息，如果实际支付价格小于对应配置的金币的价格（无缓存），则不做处理
        VipPriceInfo vipPriceInfoInDB = vipInfoService.getVipPriceInfoByVipId(orderInfoInDB.getItemId());
        int discountStatus = Optional.ofNullable(orderInfoInDB.getDiscountStatus()).orElse(0);

        if (discountStatus == 1) {
            double discountAmount = Optional.ofNullable(orderInfoInDB.getDiscountAmount()).orElse(0d);
            vipPriceInOrder = vipPriceInOrder + discountAmount;
        }

        if (vipPriceInfoInDB == null || vipPriceInfoInDB.getVipPrice().doubleValue() > vipPriceInOrder) {
            return;
        }

        //变更订单信息
        orderInfo.setModifyTime(DateUtil.getCurDate());
        orderInfoMapper.updateOrdeInfoStatus(orderInfo);

        if (orderInfoInDB.getTransType().intValue() == SysConstant.ORDER_TRANS_TYPE_PURCHASE_VIP) {

            //获取当前用户已经购买的会员信息
            Integer userId = orderInfoInDB.getUserId();

            //更新用户VIP状态
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(userId);
            userInfo.setVipStatus(1);
            userInfo.setModifyTime(DateUtil.getCurDate());

            userInfoService.modifyUserVipStatus(userInfo);

            //获取会员有效时间
            int vipValidPeriod = vipPriceInfoInDB.getValidPeriod();

            UserVipValidInfo userVipValidInfoInDB = vipInfoService.getVipValidInfo(userId);

            //如果没有查到购买信息，说明是第一次购买
            Integer newFlag=0;
            if (userVipValidInfoInDB == null) {
                newFlag=1;
                UserVipValidInfo vipValidInfo = new UserVipValidInfo();
                vipValidInfo.setUserId(userId);
                vipValidInfo.setBeginTime(DateUtil.getCurDate());
                //vipValidInfo.setEndTime(DateUtil.getVipEndTime(DateUtil.getCurDate(), vipPriceInfoInDB.getVipLev())); // 屏蔽于 20200303
                DateTime endTime = new DateTime(DateUtil.getCurDate()); //20200303
                vipValidInfo.setEndTime(endTime.plusDays(vipPriceInfoInDB.getValidPeriod()).toDate());

                vipValidInfo.setVipLev(vipPriceInfoInDB.getVipLev());
                vipValidInfo.setVipStatus(1);
                vipValidInfo.setDayFriendCount(vipPriceInfoInDB.getDayFriendCount());
                vipValidInfo.setCreateTime(DateUtil.getCurDate());
                vipValidInfo.setModifyTime(DateUtil.getCurDate());
                vipInfoService.recordUserVipValidInfo(vipValidInfo);

            } else {

                UserVipValidInfo vipValidInfo = new UserVipValidInfo();
                vipValidInfo.setUserId(userVipValidInfoInDB.getUserId());
                //vipValidInfo.setEndTime(DateUtil.getVipEndTime(DateUtil.getCurDate(), vipPriceInfoInDB.getVipLev())); // 屏蔽于 20200303
                DateTime endTime = new DateTime(DateUtil.getCurDate()); //20200303

                if(userVipValidInfoInDB.getEndTime()!=null && userVipValidInfoInDB.getEndTime().compareTo(DateUtil.getCurDate())>0){  //20200720 ,续费时间以结束 时间为准
                    endTime=new DateTime(userVipValidInfoInDB.getEndTime());
                }

                vipValidInfo.setEndTime(endTime.plusDays(vipPriceInfoInDB.getValidPeriod()).toDate());

                vipValidInfo.setVipLev(vipPriceInfoInDB.getVipLev());
                vipValidInfo.setVipStatus(1);
                vipValidInfo.setDayFriendCount(vipPriceInfoInDB.getDayFriendCount());
                vipValidInfo.setModifyTime(DateUtil.getCurDate());

                vipInfoService.modifyUserVipValidInfo(vipValidInfo);

            }

            //记录购买日志
            UserVipLogInfo userVipLogInfo = new UserVipLogInfo();
            userVipLogInfo.setUserId(userId);
            userVipLogInfo.setVipLev(vipPriceInfoInDB.getVipLev());
            userVipLogInfo.setCreateTime(DateUtil.getCurDate());

            vipInfoService.recordUserVipLogInfo(userVipLogInfo);

            // 如果用户购买的是 698元(5年会员)，则设置用户的第一级推广收益为 30%
            if (orderInfoInDB.getItemId().equals(16)) {
                UserPromotionSettleInfo userPromotionSettleInfo = userPromotionSettleInfoMapper.queryUserPromotionSettleInfo(userId);

                // 如果不存在用户的推广结算信息，则新增。
                if (userPromotionSettleInfo == null) {
                    UserPromotionSettleInfo recordUserPromotionSettleInfo = new UserPromotionSettleInfo();
                    recordUserPromotionSettleInfo.setUserId(userId);
                    recordUserPromotionSettleInfo.setFirstLevelProportion(Integer.valueOf(30));
                    recordUserPromotionSettleInfo.setCreateTime(DateUtil.getCurDate());
                    userPromotionSettleInfoMapper.addPromotionSettleInfo(recordUserPromotionSettleInfo);
                } else {
                    // 如果用户的一级推广收益比率不是 30%，则更新为 30%
                    if (userPromotionSettleInfo.getFirstLevelProportion() != null && userPromotionSettleInfo.getFirstLevelProportion().intValue() != 30) {
                        UserPromotionSettleInfo updateUserPromotionSettleInfo = new UserPromotionSettleInfo();
                        updateUserPromotionSettleInfo.setId(userPromotionSettleInfo.getId());
                        updateUserPromotionSettleInfo.setFirstLevelProportion(Integer.valueOf(30));
                        updateUserPromotionSettleInfo.setModifyTime(DateUtil.getCurDate());
                        userPromotionSettleInfoMapper.updPromotionSettleInfo(updateUserPromotionSettleInfo);
                    }
                }
            }

            //添加收入记录
            //查看当前购买VIP的用户是否有推荐人

            //计算爸爸的提成(按1级)
            Integer referer = userInfoService.getUserReferer(userId);
            if (newFlag.equals(1) && referer != null) {

                //获取推荐人当前用户余额
                //double accountBalance = Optional.ofNullable(userInfoService.getUserAccountBalance(userId)).orElse(0d); //20200226 发现 有问题，取的余额 的userId不对
                double accountBalance = Optional.ofNullable(userInfoService.getUserAccountBalance(referer)).orElse(0d);

                UserInviteIncomeInfo userInviteIncomeInfo = new UserInviteIncomeInfo();
                userInviteIncomeInfo.setUserId(referer);
                userInviteIncomeInfo.setBeforeBalance(accountBalance);

                //20200226 改成按用户 的一级分成比例 计算
                Integer firstLevelProportion = 20;
                UserPromotionSettleInfo userPromotionSettleInfo = userPromotionSettleInfoMapper.queryUserPromotionSettleInfo(referer);
                if (userPromotionSettleInfo != null
                        && userPromotionSettleInfo.getFirstLevelProportion() != null
                        && userPromotionSettleInfo.getFirstLevelProportion() > 0) {
                    firstLevelProportion = userPromotionSettleInfo.getFirstLevelProportion();
                }
                //vipPriceInOrder 是原价，不是优惠价，所以这里用 orderInfo.getTotalAmount().doubleValue()，会员实际支付的 价格
                double vipSerivceBonus = Double.valueOf(orderInfo.getTotalAmount().doubleValue() * (firstLevelProportion.doubleValue() / 100)).doubleValue();
                log.info("****OrderInfoServiceImpl 支付金额:" + orderInfo.getTotalAmount()+"__vipSerivceBonus:"+vipSerivceBonus);
                userInviteIncomeInfo.setAfterBalance(accountBalance + vipSerivceBonus);
                userInviteIncomeInfo.setIncome(vipSerivceBonus);

                //获取当前用户信息
                UserInfo fromUserInfo = userInfoService.getUserBaseInfo(userId);
                userInviteIncomeInfo.setFromUserId(fromUserInfo.getUserId());
                userInviteIncomeInfo.setFromNickName(fromUserInfo.getNickName());
                userInviteIncomeInfo.setFromAvatarUrl(fromUserInfo.getAvatarUrl());
                userInviteIncomeInfo.setCreateTime(DateUtil.getCurDate());

                userInviteIncomeInfo.setLevel(1);//按一级比例计算
                userInviteIncomeInfo.setLevelProportion(firstLevelProportion);//比例
                userInviteIncomeInfo.setBase(orderInfo.getTotalAmount());//金额基数

                userInviteIncomeInfoService.recordUserInviteIncomeInfo(userInviteIncomeInfo);

                //更改用户余额
                UserInfo updateUserInfo = new UserInfo();
                updateUserInfo.setUserId(referer);
                updateUserInfo.setAccountBalance(accountBalance + vipSerivceBonus);
                log.info("****OrderInfoServiceImpl 更新用户余额___getAccountBalance:" + updateUserInfo.getAccountBalance());
                updateUserInfo.setModifyTime(DateUtil.getCurDate());
                userInfoService.modifyUserAccountBalance(updateUserInfo);

                //查询父推荐人是否为平台分成人员
                UserPromotionSettleInfo fatherUserPromotionSettleInfo = userPromotionSettleInfoService.getUserPromotionSettleInfo(referer);
                if (fatherUserPromotionSettleInfo != null && fatherUserPromotionSettleInfo.getId() != null) {

                    userPromotionSettleInfoService.processUserPromotionSettleInfo(fatherUserPromotionSettleInfo, orderInfo.getTotalAmount(), 1);

                }

//                else {  //20200226屏蔽
//
//                    //当父推荐人不是平台分成人员时，查询其祖推荐人
//                    Integer grandReferer = userInfoService.getUserReferer(referer);
//
//                    if (grandReferer != null) {
//
//                        UserPromotionSettleInfo grandFatherUserPromotionSettleInfo = userPromotionSettleInfoService.getUserPromotionSettleInfo(grandReferer);
//
//                        if (grandFatherUserPromotionSettleInfo != null && grandFatherUserPromotionSettleInfo.getId() != null) {
//
//                            userPromotionSettleInfoService.processUserPromotionSettleInfo(grandFatherUserPromotionSettleInfo, orderInfoInDB.getTotalAmount(), 2);
//
//                        }
//
//                    }
//
//                }

                //20200211 hyl 通知推荐人，有人开通了 vip
//                UserInfo refererUser = userInfoService.getUserBaseInfo(referer);//推荐人
//                UserInfo bRefererUser = userInfoService.getUserBaseInfo(userId);//被推荐人
//                if (refererUser != null) {
//                    log.info("****OrderInfoServiceImpl 发送VIP通知___refererUser-ID:" + refererUser.getUserId() + "___bRefererUser-ID:" + bRefererUser.getUserId());
//                    menuHandler.pushMsg(SysConstant.BUY_VIP_REFERER_PUSH_MSG
//                                    .replace(SysConstant.frontDomain, platformSysInfoConfig.getFrontDomain())
//                                    .replace("[username]", bRefererUser.getNickName())
//                                    .replace("[income]", String.format("%.2f", userInviteIncomeInfo.getIncome())),
//                            refererUser.getOpenId(), weixinService);
//                }
               pushBuyVip(referer,userId,userInviteIncomeInfo.getIncome(),platformSysInfo,  weixinService);
                //20200211 hyl 通知推荐人，有人开通了 vip

                //上面是计算爸爸的
                //下面try中是计算爷爷的
                try{
                    updateAccountBalance2(referer,orderInfo.getTotalAmount(),fromUserInfo,platformSysInfo, weixinService);
                }catch (Exception e){
                    log.info("****updateAccountBalance2 计算二级推荐人报错:" + e.getMessage()+"__referer:"+referer);
                }

            }

            //查询当前购买用户是否是置顶品牌下的用户
            BrandInfo userSelectBrandInfo = userBrandInfoService.getUserSelectBrandInfo(userId);
            if (userSelectBrandInfo != null && userSelectBrandInfo.getId() != null) {

                //查询品牌推广用户信息
                BrandPromotionSettleInfo brandPromotionSettleInfo = brandPromotionSettleInfoService.getBrandPromotionSettleInfo(userSelectBrandInfo.getId());

                if (brandPromotionSettleInfo != null && brandPromotionSettleInfo.getId() != null) {

                    //处理金额
                    brandPromotionSettleInfoService.processUserPromotionSettleInfo(brandPromotionSettleInfo, orderInfoInDB.getTotalAmount());

                    //添加付费用户信息
                    BrandPromotionPayUserInfo brandPromotionPayUserInfo = new BrandPromotionPayUserInfo();
                    brandPromotionPayUserInfo.setBrandId(userSelectBrandInfo.getId());
                    brandPromotionPayUserInfo.setUserId(userId);
                    brandPromotionPayUserInfo.setPayAmount(orderInfoInDB.getTotalAmount());
                    brandPromotionPayUserInfo.setPayDesc("购买高级会员");
                    brandPromotionPayUserInfo.setCreateTime(DateUtil.getCurDate());
                    brandPromotionPayUserInfo.setBrandAgentId(brandPromotionSettleInfo.getUserId());
                    brandPromotionPayUserInfo.setOrderId(orderInfoInDB.getOrderId());
                    brandPromotionPayUserInfoService.recordBrandPromotionPayUserInfo(brandPromotionPayUserInfo);
                }
            }

            //删除虚拟访问
            String virtualUserInfo = SysConstant.NORMAL_VIRTUAL_VISIT_USERS;

            //String profile = SpringContextUtil.getActiveProfile();
//            if (SysConstant.PROFILES_ACTIVE_DEV.equals(profile)) {
//
//                virtualUserInfo = SysConstant.TEST_VIRTUAL_VISIT_USERS;
//
//            }
            List<String> virtualUsers = Arrays.asList(virtualUserInfo.split(","));
            lookArticleInfoService.removeVirtualVisitUsers(virtualUsers, userId);
            // 20200505 yl 发送开通vip成功消息 start
            try {
                UserVipValidInfo userVipValidInfo = vipInfoService.getVipValidInfo(userId);
                UserInfo userMainInfo = userInfoService.getUserMainInfo(userId);
                this.buyVipMessagePush(userMainInfo,userVipValidInfo,platformSysInfo, weixinService);
            } catch (Exception e) {
                log.info("****buyVipMessagePush 向购买会员用户推送消息报错:" + e.getMessage() + "__userId:" + userId);
            }
            // 20200505 yl 发送开通vip成功消息 end

        }

        //佣金余额更新 20201029 start

        try {
            Integer ordUserId = Integer.valueOf(orderInfoInDB.getUserId());

            //佣金余额在 redis 里面的 Key（keyStr）
            String keyStr;
            keyStr = WECHATPAYACCOUNTBALANCELAST + orderInfo.getOrderId() + ordUserId;

            if (keyStr != null && !"".equals(keyStr.trim())) {

                // 获取 redis 记录的佣金余额
                Double newcCount = (Double) redisCacheUtil.getCacheObject(keyStr);
                Double oldCount,count;

                if (newcCount != null) {

                    // 查询更新前 userinfo 的佣金余额
                    UserInfo ordUserInfo = userInfoService.getUserMainInfo(ordUserId);
                    oldCount = ordUserInfo.getAccountBalance();

                    // 计算本次抵扣(变动)佣金的金额
                    count = newcCount - oldCount;

                    // 1.变动表：b_user_invite_income_info,添加一条佣金变动记录
                    UserInviteIncomeInfo ordUserInviteIncomeInfo = new UserInviteIncomeInfo();
                    ordUserInviteIncomeInfo.setUserId(ordUserId);// 变动用户ID
                    ordUserInviteIncomeInfo.setBeforeBalance(oldCount);// 变动前佣金余额
                    ordUserInviteIncomeInfo.setAfterBalance(newcCount);// 变动后佣金余额
                    ordUserInviteIncomeInfo.setFromUserId(ordUserInfo.getUserId());
                    ordUserInviteIncomeInfo.setFromNickName(ordUserInfo.getNickName());
                    ordUserInviteIncomeInfo.setFromAvatarUrl(ordUserInfo.getAvatarUrl());
                    ordUserInviteIncomeInfo.setIncome(count);// 变动佣金金额
                    ordUserInviteIncomeInfo.setCreateTime(DateUtil.getCurDate());// 创建时间
//                    ordUserInviteIncomeInfo.setLevel(1);//按一级比例计算
//                    ordUserInviteIncomeInfo.setLevelProportion(1);//比例
                    ordUserInviteIncomeInfo.setBase(orderInfo.getTotalAmount());//金额基数,交易金额

                    userInviteIncomeInfoService.recordUserInviteIncomeInfo(ordUserInviteIncomeInfo);

                    // 2.佣金汇总：b_user_promotion_settle_info,汇总佣金记录
                    // 查询用户的汇总佣金记录
                    UserPromotionSettleInfo ordUserPromotionSettleInfo = userPromotionSettleInfoMapper.queryUserPromotionSettleInfo(ordUserId);
                    if (ordUserPromotionSettleInfo != null) {

                        userPromotionSettleInfoService.processUserPromotionSettleInfo(ordUserPromotionSettleInfo, -count, 6);

                    }

                    // 3.更新 userinfo 的佣金余额
                    ordUserInfo.setAccountBalance(newcCount);
                    ordUserInfo.setModifyTime(DateUtil.getCurDate());
                    this.userInfoService.modifyUserAccountBalance(ordUserInfo);


                    // 4.删除redis佣金余额缓存
                    redisCacheUtil.removeSingleCache(keyStr);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //佣金余额更新 20201029 end

    }

    @Override
    public void doPayCallBackProcessForBusiness(OrderInfo orderInfo) {
        double monetary = orderInfo.getTotalAmount().doubleValue(); //交易总计金额

        // 根据订单ID获取订单信息
        OrderInfo orderInfoInDB = orderInfoMapper.queryOrderSimpleInfo(orderInfo.getOrderId());
        if (orderInfoInDB == null) {
            return;
        }

        // 如果实际支付价格小于数据库中订单价格，则不做处理
        if (orderInfoInDB.getTotalAmount().doubleValue() > monetary) {
            return;
        }

        // 如果订单状态为已经处理，则不做处理
        if (orderInfoInDB.getTransStatus().intValue() != SysConstant.ORDER_PRE_PAY_STATUS) {
            return;
        }

        //变更订单信息 ==== 订单状态 1-已支付
        orderInfo.setTransStatus(SysConstant.ORDER_ALREADY_PAY_STATUS);
        orderInfo.setModifyTime(DateUtil.getCurDate());
        orderInfoMapper.updateOrdeInfoStatus(orderInfo);

        // 订单交易类型 2-商学院课程订单
//        if (orderInfoInDB.getTransType().intValue() == SysConstant.ORDER_TRANS_TYPE_PURCHASE_BUSINESS) {
//
//        }
    }

    /**
     * 根据 买家用户USERID 购买商品id,课程ID 商学院课程订单信息 0-未购买 1-已购买
     */
    @Override
    public int checkCourse(Integer userId, Integer courseId) {

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);//买家用户USERID
        orderInfo.setItemId(courseId);//购买商品id,课程ID
//        orderInfo.setSubject("购买商学院课程服务");//交易说明
        orderInfo.setTransStatus(1);//交易状态 0-等待支付 1-已支付 2-已退款
        orderInfo.setTransType(2);//订单交易类型 2-商学院课程订单
//        orderInfo.setTransStatus(SysConstant.ORDER_ALREADY_PAY_STATUS);//交易状态 0-等待支付 1-已支付 2-已退款
//        orderInfo.setTransType(SysConstant.ORDER_TRANS_TYPE_PURCHASE_BUSINESS);//订单交易类型 2-商学院课程订单

        OrderInfo orderInfoDto =  orderInfoMapper.selectPayForCourse(orderInfo);
        if(orderInfoDto != null){
            return 1;
        }
        return 0;
    }

    /**
     * 查询多条数据
     *
     * @param pageNum 查询起始位置
     * @param pageSize  查询条数
     * @param orderInfo 实例对象
     * @return 对象列表
     */
    @Override
    public PageInfo selectAllCourseId(Integer pageNum, Integer pageSize, OrderInfo orderInfo) {

        PageHelper.startPage(pageNum, pageSize);

        //        orderInfo.setItemId(courseId);//购买商品id,课程ID
        orderInfo.setTransStatus(1);//交易状态 0-等待支付 1-已支付 2-已退款
        orderInfo.setTransType(2);//订单交易类型 2-商学院课程订单

        List<OrderInfo> orderInfoList = this.orderInfoMapper.selectAllCourseId(orderInfo);

        return new PageInfo<OrderInfo>(orderInfoList);
    }



    @Override
    public OrderInfo getOrderSimpleInfo(String orderId) {
        return orderInfoMapper.queryOrderSimpleInfo(orderId);
    }

    @Override
    public int queryTodayOrderCount(Integer userId) {
        return orderInfoMapper.queryTodayOrderCount(userId);
    }

    /**20200505 yl
     * 购买vip后 进行模板消息推送
     * @param user
     * @param userVipValidInfo
     */
    private void buyVipMessagePush(UserInfo user,UserVipValidInfo userVipValidInfo,PlatformSysInfo platformSysInfo, WxMpServiceImpl  weixinService) throws WxErrorException, InterruptedException {

        //region （公众号做通）20210902
        if(user!=null && !user.getGzhCode().equals(platformSysInfo.getSysGzh().getGzhCode())){
            UserGroupOpenId userGroupOpenId= userGroupGzhService.getUserOpenId(platformSysInfo.getSysGzh().getGzhCode(),user.getUserId());
            if(userGroupOpenId!=null){
                user.setOpenId(userGroupOpenId.getOpenId());
            }
        }
        //endregion

        if (user.getOpenId() != null) {

            String isActivity = messageDictInfoService.getConfigValueByKey(SysConstant.IsActivity);

            if (isActivity.equals("1")) { // 发送模板消息接口 (活动)

                menuHandler.pushMsg(SysConstant.MAIYISONGYI_PUSH_MSG, user.getOpenId(), weixinService);
                msgHandler.returnKF((WeixinServiceDL) weixinService, user.getOpenId(), platformSysInfo);

                // 国庆先发头像链接
//                Thread.sleep(10000);
//                String SEND_NATIONAL_DAY_PUSH_MSG = "<a href=\"" + platformSysInfo.getHeadSculptureMenuUrl() + "\">✨迎接国庆,我们一起换头像>></a>";
//                WxMpKefuMessage messageDay = WxMpKefuMessage.TEXT().toUser(user.getOpenId()).content(SEND_NATIONAL_DAY_PUSH_MSG).build();
//                weixinService.getKefuService().sendKefuMessage(messageDay);


            } else {

                // 发送模板消息接口 (平时)

                WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                        // 接收者openid
                        .toUser(user.getOpenId())
                        .templateId(platformSysInfo.getSysGzh().getBuyVipMessagePushTempId())
                        .url(platformSysInfo.getArticleListMenuUrl())
                        .build();
                String firstMsg = user.getNickName() + "您的会员账号已经开通，尽情使用吧！\n\n";
                String remarkMsg = "如有疑问，可回复【客服】来了解详情。\n\n";

                // 添加模板数据
                templateMessage.addData(new WxMpTemplateData("first", firstMsg, "#FF00FF"))
                        .addData(new WxMpTemplateData("keyword1", user.getNickName(), "#A9A9A9"))
                        .addData(new WxMpTemplateData("keyword2", DateUtil.getFormatDate(null, userVipValidInfo.getModifyTime()), "#A9A9A9"))
                        .addData(new WxMpTemplateData("keyword3", DateUtil.getFormatDate(null, userVipValidInfo.getEndTime()), "#A9A9A9"))
                        .addData(new WxMpTemplateData("remark", remarkMsg, "#0000FF"));
                String msgId = null;
                try {
                    // 发送模板消息
                    msgId = weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                    log.info("开通会员推送成功：openId:" + user.getOpenId() + "_userId:" + user.getUserId());
                } catch (WxErrorException e) {
                    //e.printStackTrace();
                }
            }
        }
    }

    /**20200505 yl
     * 佣金结算成功通知
     * @param referer
     * @param userId
     * @param income
     */
    private void pushBuyVip(Integer referer,Integer userId,Double income,PlatformSysInfo platformSysInfo, WxMpServiceImpl  weixinService){
        UserInfo refererUser = userInfoService.getUserBaseInfo(referer);//推荐人
        UserInfo bRefererUser = userInfoService.getUserBaseInfo(userId);//被推荐人

        //屏蔽于 20200507 hyl
//        if (refererUser != null) {
//            log.info("****OrderInfoServiceImpl 发送VIP通知___refererUser-ID:" + refererUser.getUserId() + "___bRefererUser-ID:" + bRefererUser.getUserId());
//            menuHandler.pushMsg(SysConstant.BUY_VIP_REFERER_PUSH_MSG
//                            .replace(SysConstant.frontDomain, platformSysInfoConfig.getFrontDomain())
//                            .replace("[username]", bRefererUser.getNickName())
//                            .replace("[income]", String.format("%.2f", income)),
//                    refererUser.getOpenId(), weixinService);
//        }

        //region （公众号做通）20210902
        if(refererUser!=null && !refererUser.getGzhCode().equals(platformSysInfo.getSysGzh().getGzhCode())){
            UserGroupOpenId userGroupOpenId= userGroupGzhService.getUserOpenId(platformSysInfo.getSysGzh().getGzhCode(),referer);
            if(userGroupOpenId!=null){
                refererUser.setOpenId(userGroupOpenId.getOpenId());
            }
        }
        //endregion

        if (refererUser != null && refererUser.getOpenId() != null) {
            // 发送模板消息接口
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    // 接收者openid
                    .toUser(refererUser.getOpenId())
                    // 模板id
//                    .templateId(pushBuyVipTempID)
                    .templateId(platformSysInfo.getSysGzh().getPushBuyVipTempId())
                    // 模板跳转链接
//                    .url(platformSysInfoConfig.getFrontDomain()+ "/pages/setting/commission.html")
                    .url(platformSysInfo.getFrontDomain()+ "/pages/setting/commission.html")
                    .build();
            String firstMsg ="恭喜您，一笔佣金结算成功!\n\n";
            String remarkMsg = "点击查看佣金详细明细。\n\n";

            // 添加模板数据
            templateMessage.addData(new WxMpTemplateData("first", firstMsg, "#FF00FF"))
                    .addData(new WxMpTemplateData("keyword1",bRefererUser.getNickName(), "#A9A9A9"))
                    .addData(new WxMpTemplateData("keyword2", DateUtil.getFormatDate(null,DateUtil.getCurDate()), "#A9A9A9"))
                    .addData(new WxMpTemplateData("keyword3", "佣金分成", "#A9A9A9"))
                    .addData(new WxMpTemplateData("keyword4", "消费提成", "#A9A9A9"))
                    .addData(new WxMpTemplateData("keyword5", String.valueOf(income), "#A9A9A9"))
                    .addData(new WxMpTemplateData("remark", remarkMsg, "#0000FF"));
            String msgId = null;
            try {
                // 发送模板消息
                msgId = weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                log.error("佣金推送成功：openId:"+refererUser.getOpenId()+"_userId:"+refererUser.getUserId());
            } catch (WxErrorException e) {
                //e.printStackTrace();
            }
        }
    }

//  计算爷爷的
    private void updateAccountBalance2(Integer userId,Double totalAmount,UserInfo fromUserInfo,PlatformSysInfo platformSysInfo, WxMpServiceImpl  weixinService) {
        Integer referer = userInfoService.getUserReferer(userId);
        if (referer != null) {

            Integer secondLevelProportion = 0;
            UserPromotionSettleInfo userPromotionSettleInfo = userPromotionSettleInfoMapper.queryUserPromotionSettleInfo(referer);
            if (userPromotionSettleInfo != null
                    && userPromotionSettleInfo.getSecondLevelProportion() != null
                    && userPromotionSettleInfo.getSecondLevelProportion() > 0) {
                secondLevelProportion = userPromotionSettleInfo.getSecondLevelProportion();

                //获取推荐人当前用户余额
                double accountBalance = Optional.ofNullable(userInfoService.getUserAccountBalance(referer)).orElse(0d);

                UserInviteIncomeInfo userInviteIncomeInfo = new UserInviteIncomeInfo();
                userInviteIncomeInfo.setUserId(referer);
                userInviteIncomeInfo.setBeforeBalance(accountBalance);
                //vipPriceInOrder 是原价，不是优惠价，所以这里用 orderInfo.getTotalAmount().doubleValue()，会员实际支付的 价格
                double vipSerivceBonus = Double.valueOf(totalAmount.doubleValue() * (secondLevelProportion.doubleValue() / 100)).doubleValue();
                log.info("****updateAccountBalance2 支付金额:" + totalAmount + "__vipSerivceBonus:" + vipSerivceBonus);
                userInviteIncomeInfo.setAfterBalance(accountBalance + vipSerivceBonus);
                userInviteIncomeInfo.setIncome(vipSerivceBonus);

                //获取当前用户信息
                //UserInfo fromUserInfo = userInfoService.getUserBaseInfo(userId);
                userInviteIncomeInfo.setFromUserId(fromUserInfo.getUserId());
                userInviteIncomeInfo.setFromNickName(fromUserInfo.getNickName());
                userInviteIncomeInfo.setFromAvatarUrl(fromUserInfo.getAvatarUrl());
                userInviteIncomeInfo.setCreateTime(DateUtil.getCurDate());
                userInviteIncomeInfo.setLevel(2);//按一级比例计算
                userInviteIncomeInfo.setLevelProportion(secondLevelProportion);//比例
                userInviteIncomeInfo.setBase(totalAmount);//金额基数

                userInviteIncomeInfoService.recordUserInviteIncomeInfo(userInviteIncomeInfo);

                //更改用户余额
                UserInfo updateUserInfo = new UserInfo();
                updateUserInfo.setUserId(referer);
                updateUserInfo.setAccountBalance(accountBalance + vipSerivceBonus);
                log.info("****updateAccountBalance2 更新用户余额___getAccountBalance:" + updateUserInfo.getAccountBalance());
                updateUserInfo.setModifyTime(DateUtil.getCurDate());
                userInfoService.modifyUserAccountBalance(updateUserInfo);

                //更新二级 收入和总收入
                userPromotionSettleInfoService.processUserPromotionSettleInfo(userPromotionSettleInfo, totalAmount, 2);

                pushBuyVip(referer,fromUserInfo.getUserId(),userInviteIncomeInfo.getIncome(),platformSysInfo, weixinService);

                //上面是计算爷爷的
                //下面try中是计算太爷的
                try {
                    updateAccountBalance3(referer, totalAmount, fromUserInfo,platformSysInfo, weixinService);
                } catch (Exception e) {
                    log.info("****updateAccountBalance3 计算三级推荐人报错:" + e.getMessage() + "__referer:" + referer);
                }
            }
        }
    }

    //  计算太爷的
    private void updateAccountBalance3(Integer userId,Double totalAmount,UserInfo fromUserInfo,PlatformSysInfo platformSysInfo, WxMpServiceImpl  weixinService){
        Integer referer = userInfoService.getUserReferer(userId);
        if (referer != null) {

            Integer thirdLevelProportion = 0;
            UserPromotionSettleInfo userPromotionSettleInfo = userPromotionSettleInfoMapper.queryUserPromotionSettleInfo(referer);
            if (userPromotionSettleInfo != null
                    && userPromotionSettleInfo.getThirdLevelProportion() != null
                    && userPromotionSettleInfo.getThirdLevelProportion() > 0) {
                thirdLevelProportion = userPromotionSettleInfo.getThirdLevelProportion();

                //获取推荐人当前用户余额
                double accountBalance = Optional.ofNullable(userInfoService.getUserAccountBalance(referer)).orElse(0d);

                UserInviteIncomeInfo userInviteIncomeInfo = new UserInviteIncomeInfo();
                userInviteIncomeInfo.setUserId(referer);
                userInviteIncomeInfo.setBeforeBalance(accountBalance);
                //vipPriceInOrder 是原价，不是优惠价，所以这里用 orderInfo.getTotalAmount().doubleValue()，会员实际支付的 价格
                double vipSerivceBonus = Double.valueOf(totalAmount.doubleValue() * (thirdLevelProportion.doubleValue() / 100)).doubleValue();
                log.info("****updateAccountBalance3 支付金额:" + totalAmount + "__vipSerivceBonus:" + vipSerivceBonus);
                userInviteIncomeInfo.setAfterBalance(accountBalance + vipSerivceBonus);
                userInviteIncomeInfo.setIncome(vipSerivceBonus);

                //获取当前用户信息
                //UserInfo fromUserInfo = userInfoService.getUserBaseInfo(userId);
                userInviteIncomeInfo.setFromUserId(fromUserInfo.getUserId());
                userInviteIncomeInfo.setFromNickName(fromUserInfo.getNickName());
                userInviteIncomeInfo.setFromAvatarUrl(fromUserInfo.getAvatarUrl());
                userInviteIncomeInfo.setCreateTime(DateUtil.getCurDate());
                userInviteIncomeInfo.setLevel(3);//按一级比例计算
                userInviteIncomeInfo.setLevelProportion(thirdLevelProportion);//比例
                userInviteIncomeInfo.setBase(totalAmount);//金额基数

                userInviteIncomeInfoService.recordUserInviteIncomeInfo(userInviteIncomeInfo);

                //更改用户余额
                UserInfo updateUserInfo = new UserInfo();
                updateUserInfo.setUserId(referer);
                updateUserInfo.setAccountBalance(accountBalance + vipSerivceBonus);
                log.info("****updateAccountBalance3 更新用户余额___getAccountBalance:" + updateUserInfo.getAccountBalance());
                updateUserInfo.setModifyTime(DateUtil.getCurDate());
                userInfoService.modifyUserAccountBalance(updateUserInfo);

                //更新三级 收入和总收入
                userPromotionSettleInfoService.processUserPromotionSettleInfo(userPromotionSettleInfo, totalAmount, 3);

              pushBuyVip(referer,fromUserInfo.getUserId(),userInviteIncomeInfo.getIncome(),platformSysInfo, weixinService);
                //上面是计算太爷的
                //下面try中是计算太太爷的
                try {
                    updateAccountBalance4(referer, totalAmount, fromUserInfo,platformSysInfo, weixinService);
                } catch (Exception e) {
                    log.info("****updateAccountBalance4 计算四级推荐人报错:" + e.getMessage() + "__referer:" + referer);
                }
            }
        }
    }

    //  计算太太爷的  yl 20200518 四级
    private void updateAccountBalance4(Integer userId,Double totalAmount,UserInfo fromUserInfo,PlatformSysInfo platformSysInfo, WxMpServiceImpl  weixinService){
        Integer referer = userInfoService.getUserReferer(userId);
        if (referer != null) {
            Integer fourthLevelProportion = 0;
            UserPromotionSettleInfo userPromotionSettleInfo = userPromotionSettleInfoMapper.queryUserPromotionSettleInfo(referer);
            if (userPromotionSettleInfo != null
                    && userPromotionSettleInfo.getFourthLevelProportion() != null
                    && userPromotionSettleInfo.getFourthLevelProportion() > 0) {
                fourthLevelProportion = userPromotionSettleInfo.getFourthLevelProportion();

                //获取推荐人当前用户余额
                double accountBalance = Optional.ofNullable(userInfoService.getUserAccountBalance(referer)).orElse(0d);

                UserInviteIncomeInfo userInviteIncomeInfo = new UserInviteIncomeInfo();
                userInviteIncomeInfo.setUserId(referer);
                userInviteIncomeInfo.setBeforeBalance(accountBalance);
                //vipPriceInOrder 是原价，不是优惠价，所以这里用 orderInfo.getTotalAmount().doubleValue()，会员实际支付的 价格
                double vipSerivceBonus = Double.valueOf(totalAmount.doubleValue() * (fourthLevelProportion.doubleValue() / 100)).doubleValue();
                log.info("****updateAccountBalance4 支付金额:" + totalAmount + "__vipSerivceBonus:" + vipSerivceBonus);
                userInviteIncomeInfo.setAfterBalance(accountBalance + vipSerivceBonus);
                userInviteIncomeInfo.setIncome(vipSerivceBonus);

                //获取当前用户信息
                //UserInfo fromUserInfo = userInfoService.getUserBaseInfo(userId);
                userInviteIncomeInfo.setFromUserId(fromUserInfo.getUserId());
                userInviteIncomeInfo.setFromNickName(fromUserInfo.getNickName());
                userInviteIncomeInfo.setFromAvatarUrl(fromUserInfo.getAvatarUrl());
                userInviteIncomeInfo.setCreateTime(DateUtil.getCurDate());
                userInviteIncomeInfo.setLevel(4);//按一级比例计算
                userInviteIncomeInfo.setLevelProportion(fourthLevelProportion);//比例
                userInviteIncomeInfo.setBase(totalAmount);//金额基数

                userInviteIncomeInfoService.recordUserInviteIncomeInfo(userInviteIncomeInfo);
                //更改用户余额
                UserInfo updateUserInfo = new UserInfo();
                updateUserInfo.setUserId(referer);
                updateUserInfo.setAccountBalance(accountBalance + vipSerivceBonus);
                log.info("****updateAccountBalance4 更新用户余额___getAccountBalance:" + updateUserInfo.getAccountBalance());
                updateUserInfo.setModifyTime(DateUtil.getCurDate());
                userInfoService.modifyUserAccountBalance(updateUserInfo);

                //更新四级 收入和总收入
                userPromotionSettleInfoService.processUserPromotionSettleInfo(userPromotionSettleInfo, totalAmount, 4);

               pushBuyVip(referer,fromUserInfo.getUserId(),userInviteIncomeInfo.getIncome(),platformSysInfo, weixinService);
                //上面是计算太爷的
                //下面try中是计算太太爷的
                try {
                    updateAccountBalance5(referer, totalAmount, fromUserInfo,platformSysInfo, weixinService);
                } catch (Exception e) {
                    log.info("****updateAccountBalance5 计算五级推荐人报错:" + e.getMessage() + "__referer:" + referer);
                }
            }
        }
    }

    //  计算太太太爷的  yl 20200518 五级
    private void updateAccountBalance5(Integer userId,Double totalAmount,UserInfo fromUserInfo,PlatformSysInfo platformSysInfo, WxMpServiceImpl  weixinService){
        Integer referer = userInfoService.getUserReferer(userId);
        if (referer != null) {
            Integer fifthLevelProportion = 0;
            UserPromotionSettleInfo userPromotionSettleInfo = userPromotionSettleInfoMapper.queryUserPromotionSettleInfo(referer);
            if (userPromotionSettleInfo != null
                    && userPromotionSettleInfo.getFifthLevelProportion() != null
                    && userPromotionSettleInfo.getFifthLevelProportion() > 0) {
                fifthLevelProportion = userPromotionSettleInfo.getFifthLevelProportion();
                //获取推荐人当前用户余额
                double accountBalance = Optional.ofNullable(userInfoService.getUserAccountBalance(referer)).orElse(0d);

                UserInviteIncomeInfo userInviteIncomeInfo = new UserInviteIncomeInfo();
                userInviteIncomeInfo.setUserId(referer);
                userInviteIncomeInfo.setBeforeBalance(accountBalance);
                //vipPriceInOrder 是原价，不是优惠价，所以这里用 orderInfo.getTotalAmount().doubleValue()，会员实际支付的 价格
                double vipSerivceBonus = Double.valueOf(totalAmount.doubleValue() * (fifthLevelProportion.doubleValue() / 100)).doubleValue();
                log.info("****updateAccountBalance5 支付金额:" + totalAmount + "__vipSerivceBonus:" + vipSerivceBonus);
                userInviteIncomeInfo.setAfterBalance(accountBalance + vipSerivceBonus);
                userInviteIncomeInfo.setIncome(vipSerivceBonus);

                //获取当前用户信息
                //UserInfo fromUserInfo = userInfoService.getUserBaseInfo(userId);
                userInviteIncomeInfo.setFromUserId(fromUserInfo.getUserId());
                userInviteIncomeInfo.setFromNickName(fromUserInfo.getNickName());
                userInviteIncomeInfo.setFromAvatarUrl(fromUserInfo.getAvatarUrl());
                userInviteIncomeInfo.setCreateTime(DateUtil.getCurDate());
                userInviteIncomeInfo.setLevel(5);//按一级比例计算
                userInviteIncomeInfo.setLevelProportion(fifthLevelProportion);//比例
                userInviteIncomeInfo.setBase(totalAmount);//金额基数

                userInviteIncomeInfoService.recordUserInviteIncomeInfo(userInviteIncomeInfo);

                //更改用户余额
                UserInfo updateUserInfo = new UserInfo();
                updateUserInfo.setUserId(referer);
                updateUserInfo.setAccountBalance(accountBalance + vipSerivceBonus);
                log.info("****updateAccountBalance5 更新用户余额___getAccountBalance:" + updateUserInfo.getAccountBalance());
                updateUserInfo.setModifyTime(DateUtil.getCurDate());
                userInfoService.modifyUserAccountBalance(updateUserInfo);

                //更新五级 收入和总收入
                userPromotionSettleInfoService.processUserPromotionSettleInfo(userPromotionSettleInfo, totalAmount, 5);

              pushBuyVip(referer,fromUserInfo.getUserId(),userInviteIncomeInfo.getIncome(),platformSysInfo, weixinService);
            }
        }
    }

}
